<template>
	<div class="cinema-detial">
		<div class="bg-white padding-20 detail-container">
			<el-row :gutter="20">
				<el-col :span="18">
					<h4>
						{{detailData.cinemaName}}
						<el-tag :type="tagMap[detailData.status]">{{SITE_STATUS[detailData.status]}}</el-tag>
					</h4>
				</el-col>
				<el-col :span="6" class="text-right">
          <el-button type="primary" size="small" @click="linkToEdit()">修改信息</el-button>
          <el-button type="danger" size="small" v-if="detailData.status === 'NORMAL'" @click="pauseCinema" >暂停开放</el-button>
          <el-button type="success" size="small" v-if="detailData.status === 'DISABLED'" @click="recoverCinema">恢复开放</el-button>
        </el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="8">
					站点ID
					<span class="detail-value">{{detailData.cid}}</span>
				</el-col>
				<el-col :span="8">
					所属品牌
					<span class="detail-value">{{detailData.brandName}}</span>
				</el-col>
				<el-col :span="8">
					站点级别
					<span class="detail-value">{{SITE_LEVEL[detailData.level]}}</span>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="8">
					所在地区
					<span class="detail-value">{{detailData.regionName}}</span>
				</el-col>
				<el-col :span="8">
					详细地址
					<span class="detail-value">{{detailData.address}}</span>
					<el-button
						type="primary"
						size="mini"
						@click="linkToMap"
						:disabled="!detailData.longitude || !detailData.latitude"
					>地图</el-button>
				</el-col>
				<el-col :span="8">
					状态
					<span class="detail-value">{{SITE_STATUS[detailData.status]}}</span>
				</el-col>
			</el-row>
		</div>
		<div class="bg-white padding-20 detail-container">
			<h3 class="detail-sub-title">观影信息</h3>
			<div class="search-container">
				<el-form :inline="true" ref="form" size="small">
					<el-form-item label="时间筛选">
						<el-date-picker
							v-model="rangeDate"
							type="monthrange"
							align="right"
							range-separator="至"
							start-placeholder="开始月份"
							end-placeholder="结束月份"
						></el-date-picker>
					</el-form-item>
					<el-button type="primary" @click="onSearch" size="small">查询</el-button>
					<el-button @click="onReset" size="small">重置</el-button>
				</el-form>
			</div>
			<el-table
				class="mt-20 el-table-modify"
				:data="tableData"
				border
				show-summary
				:summary-method="getSummaries"
			>
				<el-table-column prop="ym" align="center" label="日期"></el-table-column>
				<el-table-column prop="ticketQuantity" align="center" label="售票合计"></el-table-column>
				<el-table-column prop="noneZeroTicketQuantity" align="center" label="付费售票"></el-table-column>
				<el-table-column prop="zeroTicketQuantity" align="center" label="权益观影"></el-table-column>
				<el-table-column prop="paymentTotal" align="center" label="实际支付金额"></el-table-column>
				<el-table-column prop="ticketTotal" align="center" label="结算总额"></el-table-column>
				<el-table-column label="操作" align="center" fixed="right" width="100">
					<template slot-scope="scope">
						<el-button size="mini" type="text" @click="linToDetailed(scope.row)">查看明细</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				ref="pagination"
				class="mt-20"
				background
				:page-size.sync="pageOption.pageSize"
				:total="pageOption.total"
				@size-change="onSizeChange"
				@current-change="onPageChange"
				layout="slot,->,prev,pager,next,sizes,jumper"
			>
				<span class="pagination-title">
					共 {{ pageOption.total }} 条记录 第 {{ pageOption.page }} /
					{{ pageOption.pageTotal }} 页
				</span>
			</el-pagination>

			<div class="detail-toolbar">
				<el-button size="small" @click="cancel">取消</el-button>
			</div>
		</div>
	</div>
</template>

<script>
import moment from 'moment';
import {
	SITE_STATUS,
	SITE_LEVEL,
	pickerOptions,
	momentFormatStr
} from "@/utils/const";
import { cinemaDetail, cinemaViewData, cinemaPause, cinemaRecover } from "@/api/cinema";

export default {
	name: "CinemaDetail",
	data() {
		this.SITE_STATUS = SITE_STATUS;
		this.SITE_LEVEL = SITE_LEVEL;
		this.tagMap = {
			NORMAL: "",
			DISABLED: "danger",
			EDITING: "warning"
    };
    
    this.allData = [];

		return {
			detailData: {},
			rangeDate: [new Date(), new Date()],
			tableData: [],
			pageOption: {
				page: 1,
				pageSize: 20,
				total: 0,
				pageTotal: 1
			}
		};
	},
	computed: {},
	methods: {
		cancel() {
			this.$router.go(-1);
		},
		linkToMap() {
			const { longitude, latitude, cinemaName, address } = this.detailData;
			if (longitude && latitude) {
				return window.open(
					`http://api.map.baidu.com/marker?location=${latitude},${longitude}&title=${cinemaName}&content=${address}&output=html&src=猩猩送`
				);
			} else {
				return "";
			}
		},
		linkToMovie() {
			this.$router.push({ name: "movieOrderMgt" });
		},
		async requestDetial(id) {
			try {
				const { data } = await cinemaDetail(id);
				this.detailData = data;
				this.requestData();
			} catch (error) {}
		},
		onSearch() {
			this.pageOption.page = 1;
			this.requestData();
		},
		onReset() {
			this.pageOption.page = 1;
			this.rangeDate = [new Date(), new Date()];
			this.requestData();
		},
		async requestData() {
			const { page, pageSize: size } = this.pageOption;
			let params = {
				id: this.detailData.id
			};
			if (this.rangeDate[0]) {
				params.start = moment(this.rangeDate[0]).format(momentFormatStr.month);
				params.end = moment(this.rangeDate[1]).format(momentFormatStr.month);
			}

			const { data } = await cinemaViewData(params);
			this.allData = data;
			this.tableData = data.slice((page - 1) * size, size);

			this.pageOption.total = data.length;
			this.pageOption.pageTotal = data.length
				? Math.ceil(data.length / size)
				: 1;

			if (this.$refs.pagination) {
				let childrenRefs = this.$refs.pagination.$children;
				this.$nextTick(() => {
					childrenRefs.forEach(child => child.$forceUpdate());
				});
			}
		},
		onSizeChange(size) {
			const { page } = this.pageOption;
			this.pageOption.pageSize = size;
			this.pageOption.pageTotal = this.allData.length
				? Math.ceil(this.allData.length / size)
				: 1;
			this.tableData = this.allData.slice((page - 1) * size, size);
		},
		onPageChange(page) {
			this.pageOption.page = page;
			this.tableData = this.allData.slice(
				(page - 1) * this.pageOption.pageSize,
				page * this.pageOption.pageSize
			);
		},
		getSummaries(param) {
			const { columns } = param;
			const sums = [];
			columns.forEach((column, index) => {
				if (index === 0) {
					sums[index] = "合计";
					return;
				}
				const values = this.allData.map(item => Number(item[column.property]));
				if (!values.every(value => isNaN(value))) {
					sums[index] = values.reduce((prev, curr) => {
						const value = Number(curr);
						if (!isNaN(value)) {
							return prev + curr;
						} else {
							return prev;
						}
					}, 0);
				} else {
					sums[index] = "";
				}
			});
			return sums;
    },
    linkToEdit() {
      this.$router.push({name: 'editCinema', params: {id: this.detailData.id}});
    },
    linToDetailed(row) {
      let rangeDate = [moment(row.ym, momentFormatStr.month).startOf('month'), moment(row.ym, momentFormatStr.month).endOf('month')];
      this.$router.push({name: 'movieOrderMgt', params: {siteId: this.detailData.id, rangeDate: rangeDate}});
    },
    async pauseCinema(row) {
      this.$confirm('确定要暂停开放该站点吗？<br/>暂停后该站点将无法正常使用', {
        type: 'warning',
        dangerouslyUseHTMLString: true,
        callback: async (action) => {
          if (action == 'confirm') {
            const {data} = await cinemaPause(this.detailData.id);
            this.requestDetial(this.detailData.id);
          }
        }
      });
    },
    async recoverCinema(row) {
      this.$confirm('确定要恢复开放该站点吗？', {
        type: 'warning',
        callback: async (action) => {
          if (action == 'confirm') {
            const {data} = await cinemaRecover(this.detailData.id);
            this.requestDetial(this.detailData.id);
          }
        }
      });
    }
	},
	created() {
		let { id } = this.$route.params;
		if (id) {
			this.requestDetial(id);
		} else {
			this.cancel();
		}
	}
};
</script>

<style lang="scss">
.cinema-detial{
  margin: 20px;

  .detail-sub-title{
    margin-top: 0;
  }
}
.bg-white{
  margin-top: 20px;
  border-radius: 4px;
  background: #ffffff;
}
</style>